package top.ffhome.system.config.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

import top.ffhome.system.entity.SysUser;
import top.ffhome.system.service.SysUserService;

public class ShiroRealm extends AuthorizingRealm {
	@Autowired
	private SysUserService userService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String account = (String) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo s = new SimpleAuthorizationInfo();
		s.setStringPermissions(userService.selectPermsByAccount(account));
		return s;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String account = token.getPrincipal().toString();
		SysUser user = userService.selectByAccount(account);
		if (ObjectUtils.isEmpty(user)) {
			throw new UnknownAccountException();
		}
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(account, user.getPassword(),
				ByteSource.Util.bytes(user.getSalt()), getName());
		return info;
	}
}
